package com.agriculture.service.impl;

import com.agriculture.domain.Order;
import com.agriculture.domain.OrderStatusHistory;
import com.agriculture.dto.Order.OrderCancelRequest;
import com.agriculture.dto.Order.OrderStatusUpdateRequest;
import com.agriculture.mapper.OrderMapper;
import com.agriculture.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.agriculture.domain.Inventory;
import com.agriculture.mapper.InventoryMapper;
import com.agriculture.domain.OrderItem;
import com.agriculture.mapper.OrderItemMapper;
import com.agriculture.domain.Product;
import com.agriculture.mapper.ProductMapper;

import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
    
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public Order updateOrderStatus(Long orderId, OrderStatusUpdateRequest request) {
        // 1. 验证订单是否存在
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 更新订单状态
        int rows = orderMapper.updateOrderStatus(
            orderId,
            request.getStatus(),
            request.getOperator(),
            request.getNotes()
        );

        if (rows != 1) {
            throw new RuntimeException("更新订单状态失败");
        }

        // 3. 记录订单状态变更历史
        OrderStatusHistory history = new OrderStatusHistory();
        history.setOrderId(orderId);
        history.setStatus(request.getStatus());
        history.setOperator(request.getOperator());
        history.setNotes(request.getNotes());
        orderMapper.insertOrderHistory(history);

        logger.info("订单状态已更新: orderId={}, status={}, operator={}", 
                orderId, request.getStatus(), request.getOperator());

        // 4. 返回更新后的订单
        return orderMapper.findById(orderId);
    }

    @Override
    @Transactional
    public void cancelOrder(Long orderId, OrderCancelRequest request) {
        // 1. 验证订单是否存在
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 验证订单状态是否可以取消
        if (!canCancelOrder(order.getStatus())) {
            throw new RuntimeException("当前订单状态不可取消");
        }

        // 3. 更新订单状态
        int rows = orderMapper.updateOrderStatus(
            orderId,
            "cancelled",
            request.getCancelledBy(),
            request.getReason()
        );

        if (rows != 1) {
            throw new RuntimeException("取消订单失败");
        }

        // 4. 记录订单状态变更历史
        OrderStatusHistory history = new OrderStatusHistory();
        history.setOrderId(orderId);
        history.setStatus("cancelled");
        history.setOperator(request.getCancelledBy());
        history.setNotes(request.getReason());
        orderMapper.insertOrderHistory(history);

        logger.info("订单已取消: orderId={}, reason={}, cancelledBy={}", 
                orderId, request.getReason(), request.getCancelledBy());
    }

    private boolean canCancelOrder(String status) {
        // 定义可取消的状态列表
        Set<String> cancellableStatuses = Set.of(
            "pending_review",
            "pending_acceptance",
            "pending_shipment"
        );
        return cancellableStatuses.contains(status);
    }

    @Override
    public Order createOrder(Order order) {
        // TODO: 实现创建订单逻辑
        throw new UnsupportedOperationException("方法尚未实现");
    }

    @Override
    public Order getOrderById(Long id) {
        return orderMapper.findById(id);
    }

    @Override
    public List<Order> getOrdersByBuyer(Long buyerId, String orderType) {
        // 根据buyerId和orderType查询订单
        return orderMapper.selectOrdersByBuyer(buyerId, orderType);
    }

    @Override
    public List<Order> getOrdersBySeller(Long sellerId, String orderType) {
        // 根据sellerId和orderType查询订单
        return orderMapper.selectOrdersBySeller(sellerId, orderType);
    }

    @Override
    public void updateLogistics(Long orderId, String logisticsNo) {
        // TODO: 实现更新物流信息逻辑
        throw new UnsupportedOperationException("方法尚未实现");
    }

    @Override
    public Order confirmDelivery(Long orderId) {
        // TODO: 实现确认收货逻辑
        throw new UnsupportedOperationException("方法尚未实现");
    }

    @Override
    public List<Order> getBuyOrders(String role, String status, String search, 
                                   Long buyerId, Long sellerId, int offset, int pageSize) {
        logger.info("获取采购订单列表 - role: {}, status: {}, search: {}, buyerId: {}, sellerId: {}", 
                    role, status, search, buyerId, sellerId);
        
        try {
            List<Order> orders = orderMapper.getBuyOrders(role, status, search, 
                                                         buyerId, sellerId, offset, pageSize);
            
            if (orders == null) {
                orders = new ArrayList<>();
            }
            
            logger.debug("查询到 {} 条采购订单", orders.size());
            return orders;
            
        } catch (Exception e) {
            logger.error("获取采购订单列表失败", e);
            throw new RuntimeException("获取采购订单列表失败: " + e.getMessage());
        }
    }

    @Override
    public int countBuyOrders(String role, String status, String search, 
                             Long buyerId, Long sellerId) {
        logger.info("统计采购订单数量 - role: {}, status: {}, search: {}, buyerId: {}, sellerId: {}", 
                    role, status, search, buyerId, sellerId);
        
        try {
            int count = orderMapper.countBuyOrders(role, status, search, buyerId, sellerId);
            logger.debug("统计到 {} 条采购订单", count);
            return count;
            
        } catch (Exception e) {
            logger.error("统计采购订单数量失败", e);
            throw new RuntimeException("统计采购订单数量失败: " + e.getMessage());
        }
    }

    @Override
    public List<Order> getSellOrders(String role, String status, String search, 
                                    Long sellerId, Long buyerId, int offset, int pageSize) {
        logger.info("获取销售订单列表 - role: {}, status: {}, search: {}, sellerId: {}, buyerId: {}", 
                    role, status, search, sellerId, buyerId);
        
        try {
            List<Order> orders = orderMapper.getSellOrders(role, status, search, 
                                                          sellerId, buyerId, offset, pageSize);
            
            if (orders == null) {
                orders = new ArrayList<>();
            }
            
            logger.debug("查询到 {} 条销售订单", orders.size());
            return orders;
            
        } catch (Exception e) {
            logger.error("获取销售订单列表失败", e);
            throw new RuntimeException("获取销售订单列表失败: " + e.getMessage());
        }
    }

    @Override
    public int countSellOrders(String role, String status, String search, 
                              Long sellerId, Long buyerId) {
        logger.info("统计销售订单数量 - role: {}, status: {}, search: {}, sellerId: {}, buyerId: {}", 
                    role, status, search, sellerId, buyerId);
        
        try {
            int count = orderMapper.countSellOrders(role, status, search, sellerId, buyerId);
            logger.debug("统计到 {} 条销售订单", count);
            return count;
            
        } catch (Exception e) {
            logger.error("统计销售订单数量失败", e);
            throw new RuntimeException("统计销售订单数量失败: " + e.getMessage());
        }
    }

    @Override
    public List<Order> selectCompletedBuyOrders(String role, String status, String search, 
                                               Long buyerId, Long sellerId, int offset, int pageSize) {
        return orderMapper.selectCompletedBuyOrders(role, status, search, buyerId, sellerId, offset, pageSize);
    }

    @Override
    public int countCompletedBuyOrders(String role, String status, String search, 
                                      Long buyerId, Long sellerId) {
        return orderMapper.countCompletedBuyOrders(role, status, search, buyerId, sellerId);
    }

    @Override
    @Transactional
    public void importOrderToInventory(Long orderId, Long buyerId, String operator) {
        logger.info("开始导入订单到库存 - orderId: {}, buyerId: {}, operator: {}", orderId, buyerId, operator);
        
        // 1. 获取订单及其订单项
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        logger.info("订单状态: {}", order.getStatus());
        
        // 检查订单状态
        if (!"completed".equalsIgnoreCase(order.getStatus())) {
            throw new RuntimeException("只能导入已完成的订单");
        }
        
        // 2. 获取订单项
        List<OrderItem> orderItems = orderItemMapper.findByOrderId(orderId);
        if (orderItems.isEmpty()) {
            throw new RuntimeException("订单项不存在");
        }
        logger.info("获取到 {} 个订单项", orderItems.size());
        
        // 3. 处理每个订单项
        for (OrderItem item : orderItems) {
            logger.info("处理订单项 - itemId: {}, productId: {}, quantity: {}", 
                       item.getItemId(), item.getProductId(), item.getQuantity());
            
            if (item.getProductId() == null) {
                throw new RuntimeException("订单项缺少产品ID");
            }
            
            // 获取产品信息
            Product product = productMapper.findById(item.getProductId());
            if (product == null) {
                throw new RuntimeException("产品不存在: " + item.getProductId());
            }
            
            // 检查是否已存在库存记录
            Inventory existingInventory = inventoryMapper.findByProductId(item.getProductId(), buyerId);
            
            if (existingInventory != null) {
                // 更新现有库存
                int newStock = existingInventory.getCurrent_stock() + item.getQuantity();
                inventoryMapper.updateStock(item.getProductId(), newStock, buyerId);
            } else {
                // 创建新库存记录
                Inventory inventory = new Inventory();
                inventory.setProduct_id(item.getProductId());
                inventory.setCurrent_stock(item.getQuantity());
                // 设置最小库存为当前库存的1/10
                inventory.setMinimum_stock(item.getQuantity() / 10);
                inventory.setOperator(operator);
                inventory.setOwner_id(buyerId);
                inventoryMapper.insert(inventory);
            }
        }
        
        logger.info("订单{}已成功导入库存", orderId);
    }

    @Override
    @Transactional
    public Order confirmShipment(Long orderId, String trackingNumber, OrderStatusUpdateRequest statusUpdate) {
        logger.info("处理订单发货 - orderId: {}, trackingNumber: {}", orderId, trackingNumber);
        
        // 1. 验证订单是否存在
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 2. 验证订单状态
        if (!"pending_shipment".equals(order.getStatus())) {
            throw new RuntimeException("当前订单状态不允许发货");
        }
        
        // 3. 更新订单状态和物流信息
        order.setTrackingNumber(trackingNumber);
        order.setShipmentTime(new Date());
        order.setStatus("pending_receipt");
        order.setLastOperator(statusUpdate.getOperator());
        order.setLastOperationTime(new Date());
        
        // 4. 更新数据库
        orderMapper.updateOrderShipment(order);
        
        // 5. 记录订单状态变更历史
        OrderStatusHistory history = new OrderStatusHistory();
        history.setOrderId(orderId);
        history.setStatus("pending_receipt");
        history.setOperator(statusUpdate.getOperator());
        history.setNotes(statusUpdate.getNotes());
        orderMapper.insertOrderHistory(history);
        
        logger.info("订单发货成功 - orderId: {}", orderId);
        
        // 6. 返回更新后的订单
        return orderMapper.findById(orderId);
    }
} 